﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using HRWEB.HtmlHelpers;
using System.IO;
using NPOI;
using NPOI.HSSF;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using HRWEB.Models;
using System.Web.Routing;
namespace HRWEB.Controllers
{
    [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
        hrdbEntities ent = new hrdbEntities();
        public ActionResult Index()
        {

            return View();
        }
        
        public ActionResult ListPost(string dinput,string code)
        {
            List<Post> posts = new List<Post>();
            if (!string.IsNullOrEmpty(dinput))
            {
                ViewBag.InputDeptCode = dinput;
                ViewBag.SelectedDeptCode = code;
                string deptCode = code;
                if (string.IsNullOrEmpty(deptCode))
                {
                    return View(posts);
                }
                else
                {
                    var po = ent.Posts.Where(p => p.DeptCode == deptCode).OrderBy(p=>p.JobTypeCode).ThenBy(q=>q.JobLevelCode);
                    posts = po.ToList();
                }
            }
            return View(posts.ToList());
        }
        public ActionResult AddPost(string dinput, string code)
        {
            if (!string.IsNullOrEmpty(dinput))
                ViewBag.InputDeptCode = dinput;
            ViewBag.SelectedDeptCode = code;
            return PartialView(ent.Posts.Create());
        }
        public ActionResult DeletePost(int serialNO,string dinput,string code)
        {
            var p = ent.Posts.Find(serialNO);
            if (p != null)
            {
                ent.Posts.Remove(p);
                ent.SaveChanges();
            }
            RouteValueDictionary di = new RouteValueDictionary();
            di.Add("dinput", dinput); di.Add("code", code);
            return Redirect(UrlHelper.GenerateUrl(null, "ListPost", "Admin", null, null, null, di, Url.RouteCollection, Url.RequestContext, false));
        }
        [HttpPost]
        public ActionResult ActuallyAddPost(string dinput,string code,Post nPost) {
            if (!string.IsNullOrEmpty(dinput))
                ViewBag.InputDeptCode = dinput;
            ViewBag.SelectedDeptCode = code;
            if (!string.IsNullOrEmpty(nPost.DeptCode))
            {
                nPost.JobDescription = nPost.JobDescription.Replace("\r\n", "<br/>");
                nPost.JobDescription = nPost.JobDescription.Replace(" ", "&nbsp;");
                ent.Posts.Add(nPost);
                ent.SaveChanges();
            }
            RouteValueDictionary di = new RouteValueDictionary();
            di.Add("dinput", dinput); di.Add("code", code);
            return Redirect(UrlHelper.GenerateUrl(null, "ListPost", "Admin", null, null, null, di, Url.RouteCollection, Url.RequestContext, false));
        }
        //not actually used
        public ActionResult Export()
        {
            string physicalRoot = HttpContext.Server.MapPath("/HRWEB");
            string physicalPath = physicalRoot + "/Templates/";
            string template = physicalPath + "admin核对打印表.xls";
            HSSFWorkbook wb = null;
            ISheet sheet1 = null;
            try
            {
                FileStream fs = new FileStream(template, FileMode.Open, FileAccess.Read);
                wb = new HSSFWorkbook(fs);
            }
            catch (IOException)
            {
                TempData["dmMessage"] = "服务器正忙，请稍后再试";
                return View("Admin");
            }
            sheet1 = wb.GetSheet("sheet1");
            int i = 2;
            //var s_emp = ent.TEmployees.Where(p => p.TInfoSummaries != null);
            //s_emp = s_emp.Where(p => p.TEmployeeStatus.OrderByDescending(q => q.FOperateDate).FirstOrDefault().FStatusCode == "01").OrderBy(p => p.FEmployeeID);
            //s_emp = s_emp.Take(100);
            int pageSize = 300;
            int currentPage = 0;
            int totalSize = ent.TEmployees.Where(p => p.FPublicID != null && p.FPublicID != "").Count();
            while (pageSize * currentPage < totalSize)
            {
                using (hrdbEntities ent1 = new hrdbEntities())
                {
                    var s_emp = ent1.TEmployees.AsNoTracking().Where(p => p.FPublicID != null && p.FPublicID != "").OrderBy(p => p.FEmployeeID).Skip(pageSize * currentPage).Take(pageSize);
                    foreach (var emp in s_emp)
                    {
                        IRow row = sheet1.CreateRow(i);
                        row.CreateCell(0).SetCellValue(i - 1);
                        row.CreateCell(1).SetCellValue(emp.GetDeptName());
                        row.CreateCell(2).SetCellValue(emp.FName);
                        row.CreateCell(3).SetCellValue(emp.FEmployeeID);
                        row.CreateCell(4).SetCellValue(emp.FPublicID);
                        row.CreateCell(5).SetCellValue(emp.FIntoHisDate.HasValue ? emp.FIntoHisDate.Value.ToString("yyyy-MM-dd") : "");
                        row.CreateCell(6).SetCellValue(emp.GetBelongOrgan());
                        row.CreateCell(7).SetCellValue(emp.Feedback());
                        row.CreateCell(8).SetCellValue(emp.IsSubmitted());
                        row.SetCellBorder();
                        row.Cells[7].CellStyle.WrapText = true;
                        //int cRow = emp.Feedback().Length / 35;
                        //row.HeightInPoints = 20;
                        i++;
                    }
                    currentPage++;
                }
            }
            return File(ExcelHelper.DownLoadHelper(wb, "Export.xls"), "application/vnd.ms-excel");
        }
        public ActionResult ListEmployee(string id, string inputCode, string name, string dinput,string code)
        {
            if (string.IsNullOrEmpty(dinput))
            {
                IQueryable<TEmployee> emps;
                if (!string.IsNullOrEmpty(id))
                {
                    emps = ent.TEmployees.Where(p => p.FEmployeeID == id);
                }
                else if (!string.IsNullOrEmpty(inputCode))
                {
                    emps = ent.TEmployees.Where(p => p.FInputCode.ToUpper().StartsWith(inputCode)).OrderBy(p => p.FName);
                }
                else if (!string.IsNullOrEmpty(name))
                {
                    emps = ent.TEmployees.Where(p => p.FName == name).OrderBy(p => p.FName);
                }
                else
                {
                    return PartialView(new List<TEmployee>());
                }
                emps = emps.Where(p => p.TEmployeeStatus.OrderByDescending(q => q.FValidDate).FirstOrDefault().FStatusCode == "01");
                return PartialView(emps.ToList());
            }
            else
            {
                ViewBag.InputDeptCode = dinput;
                string deptCode = code;
                if (string.IsNullOrEmpty(deptCode))
                {
                    return PartialView(new List<TEmployee>());
                }
                else
                {
                    DeptEmployeeModel dem = new DeptEmployeeModel();
                    dem.BuildFromKQDeptCode(deptCode);
                    return PartialView(dem.Employees);
                }
            }
        }
        public ActionResult ViewEmployee(string id)
        {
            TEmployee emp = ent.TEmployees.Where(p => p.FEmployeeID == id).Single();
            return View(emp);
        }
        public ActionResult UpdateEmployee(TEmployee employee, HttpPostedFileBase image)
        {
            if (image != null)
            {
                if (image.ContentType == "image/jpeg")
                {
                    using (hrdbEntities ent = new hrdbEntities())
                    {
                        var emp = ent.TEmployees.Where(p => p.FEmployeeID == employee.FEmployeeID).Single();
                        emp.FPhoto.Data = new byte[image.ContentLength];
                        image.InputStream.Read(emp.FPhoto.Data, 0, image.ContentLength);
                        emp.FPhoto.MIME = image.ContentType;
                        ent.SaveChanges();
                    }
                }
                else
                {
                    ModelState.AddModelError("WrongPhotoFormat", "请上传jpeg格式的照片");
                }
            }
            RouteValueDictionary di = new RouteValueDictionary();
            di.Add("id", employee.FEmployeeID);
            return Redirect(UrlHelper.GenerateUrl(null, "ViewEmployee", "Admin", null, null, "basicInfo", di, Url.RouteCollection, Url.RequestContext, false));
        }
        public FileContentResult GetPhoto(string id)
        {
            var ph = ent.TEmployees.Where(p => p.FEmployeeID == id).Select(p => new { Photo = p.FPhoto.Data, MIME = p.FPhoto.MIME }).Single();
            if (ph.Photo != null)
            {
                string mi = ph.MIME;
                if (ph.MIME == null || ph.MIME == "") { mi = "image/jpeg"; }
                return File(ph.Photo, mi);
            }
            else
            {
                return null;
            }
        }
        [HttpPost]
        public ActionResult UploadEduLevel(int serial)
        {
            string path = Server.MapPath("~/CertFiles/EduLevel");
            HttpPostedFileBase file = Request.Files[0];
            string ext = Path.GetExtension(file.FileName);
            if (file != null && serial != 0)
            {
                TEduStory ee = ent.TEduStories.Where(p => p.FSerialNo == serial).Single();
                var bb = ent.TEmployees.Where(p => p.FEmployeeID == ee.FEmployeeID).Single();
                string filname = bb.FPublicID + " " + bb.FName + " " + ee.TDictEduLevel.FName + " " + ee.FUniversity + ext;
                if (!string.IsNullOrEmpty(ee.Filename))
                {
                    string oriFullName = Path.Combine(path, ee.Filename);
                    if (System.IO.File.Exists(oriFullName)) System.IO.File.Delete(oriFullName);
                }
                string fullName = Path.Combine(path, filname);
                if (System.IO.File.Exists(fullName)) { System.IO.File.Delete(fullName); }
                file.SaveAs(fullName);
                ee.Filename = filname;
                ent.SaveChanges();
            }
            return null;
        }
        [HttpPost]
        public ActionResult UploadDegree(int serial)
        {
            string path = Server.MapPath("~/CertFiles/Degree");
            HttpPostedFileBase file = Request.Files[0];
            string ext = Path.GetExtension(file.FileName);
            if (file != null && serial != 0)
            {
                TDegree ee = ent.TDegrees.Where(p => p.FSerialNo == serial).Single();
                var bb = ent.TEmployees.Where(p => p.FEmployeeID == ee.FEmployeeID).Single();
                string filname = bb.FPublicID + " " + bb.FName + " " + ee.TDictDegree.FName + " " + ee.FUniversity + ext;
                if (!string.IsNullOrEmpty(ee.Filename))
                {
                    string oriFullName = Path.Combine(path, ee.Filename);
                    if (System.IO.File.Exists(oriFullName)) System.IO.File.Delete(oriFullName);
                }
                string fullName = Path.Combine(path, filname);
                if (System.IO.File.Exists(fullName)) { System.IO.File.Delete(fullName); }
                file.SaveAs(fullName);
                ee.Filename = filname;
                ent.SaveChanges();
            }
            return null;
        }
        [HttpPost]
        public ActionResult UploadTitle(int serial)
        {
            string path = Server.MapPath("~/CertFiles/Title");
            HttpPostedFileBase file = Request.Files[0];
            string ext = Path.GetExtension(file.FileName);
            if (file != null && serial != 0)
            {
                TTitle ee = ent.TTitles.Where(p => p.FSerialNo == serial).Single();
                var bb = ent.TEmployees.Where(p => p.FEmployeeID == ee.FEmployeeID).Single();
                string filname = bb.FPublicID + " " + bb.FName + " " + ee.TDictTitle.FName + ext;
                if (!string.IsNullOrEmpty(ee.Filename))
                {
                    string oriFullName = Path.Combine(path, ee.Filename);
                    if (System.IO.File.Exists(oriFullName)) System.IO.File.Delete(oriFullName);
                }
                string fullName = Path.Combine(path, filname);
                if (System.IO.File.Exists(fullName)) { System.IO.File.Delete(fullName); }
                file.SaveAs(fullName);
                ee.Filename = filname;
                ent.SaveChanges();
            }
            return null;
        }
        [HttpGet]
        public ActionResult ChangeRoles(string id)
        {
            UserRolesModel urm = new UserRolesModel(id);
            return PartialView(urm);
        }
        [HttpPost]
        public ActionResult ChangeRoles(UserRolesModel urm)
        {
            if (urm.IsDeptMaster)
            {
                if (!Roles.IsUserInRole(urm.PublicID, "DeptMaster"))
                    Roles.AddUserToRole(urm.PublicID, "DeptMaster");
            }
            else
            {
                if (Roles.IsUserInRole(urm.PublicID, "DeptMaster"))
                    Roles.RemoveUserFromRole(urm.PublicID, "DeptMaster");
            }
            if (urm.IsAdmin)
            {
                if (!Roles.IsUserInRole(urm.PublicID, "Admin"))
                    Roles.AddUserToRole(urm.PublicID, "Admin");
            }
            else
            {
                if (Roles.IsUserInRole(urm.PublicID, "Admin"))
                    Roles.RemoveUserFromRole(urm.PublicID, "Admin");
            }
            if (urm.IsEduMaster)
            {
                if (!Roles.IsUserInRole(urm.PublicID, "EduMaster"))
                    Roles.AddUserToRole(urm.PublicID, "EduMaster");
            }
            else
            {
                if (Roles.IsUserInRole(urm.PublicID, "EduMaster"))
                    Roles.RemoveUserFromRole(urm.PublicID, "EduMaster");
            }
            RouteValueDictionary di = new RouteValueDictionary();
            di.Add("id", urm.ID);
            return Redirect(UrlHelper.GenerateUrl(null, "ViewEmployee", "Admin", null, null, "adjustPerson", di, Url.RouteCollection, Url.RequestContext, false));
        }

        public ActionResult Household(string id)
        {
            var s_stories = from es in ent.THouseHolds where es.FEmployeeID == id orderby es.FRelationCode select es;
            return PartialView(s_stories.ToList());
        }
        public ActionResult EduLevel(string id)
        {
            var s_stories = from es in ent.TEduStories where es.FEmployeeID == id orderby es.FValidDate select es;
            return PartialView(s_stories.ToList());
        }
        public ActionResult Degree(string id)
        {
            var s_stories = from es in ent.TDegrees where es.FEmployeeID == id orderby es.FValidDate select es;
            return PartialView(s_stories.ToList());
        }
        public ActionResult Title(string id)
        {
            var s_stories = from es in ent.TTitles where es.FEmployeeID == id orderby es.FValidDate select es;
            return PartialView(s_stories.ToList());
        }
        public ActionResult CreateRole(string role)
        {
            if (!Roles.RoleExists(role))
            {
                Roles.CreateRole(role);
                TempData["madmin"] = "创建成功";
            }
            return View("Index");
        }

        public ActionResult ResetUser(string publicID)
        {
            if (!string.IsNullOrEmpty(publicID))
            {
                MembershipUser user = Membership.GetUser(publicID);
                if (user != null)
                {
                    if (user.IsLockedOut)
                    {
                        user.UnlockUser();
                    }
                    string p = user.ResetPassword();
                    user.ChangePassword(p, "000000");
                    TempData["madmin"] = "用户密码已经重置为000000";
                }
                else
                {
                    TempData["madmin"] = "没找到该用户";
                }
            }
            return View("Index");
        }
    }
}
